package org.example.video.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.commons.entity.UserVideoHistory;
import com.example.commons.entity.Video;
import jakarta.annotation.Resource;
import org.example.video.mapper.UserVideoHistoryMapper;
import org.example.video.service.VideoHistoryService;
import org.example.video.service.VideoService;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: authority-v3.0.7
 * @ClassName:VideoHistoryServiceImpl
 * @description: 视频历史记录 service实现类
 * @author:dyy
 * @Version 3.0
 **/

@Service
public class VideoHistoryServiceImpl extends ServiceImpl<UserVideoHistoryMapper, UserVideoHistory> implements VideoHistoryService {
    @Resource
    private UserVideoHistoryMapper historyMapper;

    @Resource
    private VideoService videoService;

    public VideoHistoryServiceImpl(UserVideoHistoryMapper historyMapper, VideoService videoService) {
        this.historyMapper = historyMapper;
        this.videoService = videoService;
    }

    @Override
    public void saveHistory(Long userId, Long videoId) {
        UserVideoHistory history = new UserVideoHistory();
        history.setUserId(userId);
        history.setVideoId(videoId);
        historyMapper.insert(history);
    }

    @Override
    public List<String> getRecentVideoNames(Long userId, int limit) {
        return historyMapper.selectList(
                        new LambdaQueryWrapper<UserVideoHistory>()
                                .eq(UserVideoHistory::getUserId, userId)
                                .orderByDesc(UserVideoHistory::getCreateTime)
                                .last("LIMIT " + limit))
                .stream()
                .map(history -> videoService.getById(history.getVideoId()).getName())
                .collect(Collectors.toList());
    }

    @Override
    public List<Video> getRecentVideos(Long userId, int limit) {
        QueryWrapper<UserVideoHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .orderByDesc("create_time")
                .last("LIMIT " + limit);
        List<UserVideoHistory> histories = list(queryWrapper);

        List<Long> videoIds = histories.stream()
                .map(UserVideoHistory::getVideoId)
                .collect(Collectors.toList());

        if (videoIds.isEmpty()) {
            return Collections.emptyList();
        }

        return videoService.listByIds(videoIds);
    }
}
